<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="140">
            <el-form-item label="任务编码" prop="taskId">
              <el-input v-model="queryParams.taskId" placeholder="请输入任务编码" clearable />
            </el-form-item>
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable />
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <supplier-select v-model="queryParams.supplierId"></supplier-select>
            </el-form-item>
            <el-form-item label="预估交期最早日期" prop="estimateEarlyDate">
              <el-date-picker
                v-model="queryParams.estimateEarlyDate"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择预估交期最早日期"
              />
            </el-form-item>
            <el-form-item label="预估交期最晚日期" prop="estimateLatestDate">
              <el-date-picker
                v-model="queryParams.estimateLatestDate"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择预估交期最晚日期"
              />
            </el-form-item>
            <div class="flex justify-end">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </div>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-text style="color: red">数据来源：运营上传完补货计划模板，审批通过之后生成的记录</el-text>

          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['purchase:purchaseTask:add']" type="primary" plain icon="Plus" @click="handleAdd"> 新增 </el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button v-hasPermi="['purchase:purchaseTask:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['purchase:purchaseTask:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button v-hasPermi="['purchase:purchaseTask:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="purchaseTaskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="" align="center" prop="purchaseTaskId" />
        <el-table-column v-if="false" label="物料Id" align="center" prop="materialId" />
        <el-table-column label="任务编码" align="center" prop="taskId" />
        <el-table-column label="物料编码" align="center" prop="materialCode" />
        <el-table-column label="供应商编码" align="center" prop="supplierCode" />
        <el-table-column label="公司名称" align="center" prop="companyName" />
        <el-table-column label="联系方式" align="center" prop="phoneNumber" />
        <el-table-column label="单价" align="center" prop="price" />
        <el-table-column label="数量" align="center" prop="amount" />
        <el-table-column label="总价" align="center" prop="totalPrice" />
        <el-table-column label="预估交期最早日期" align="center" prop="estimateEarlyDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.estimateEarlyDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预估交期最晚日期" align="center" prop="estimateLatestDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.estimateLatestDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['purchase:purchaseTask:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['purchase:purchaseTask:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改采购任务对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" append-to-body>
      <el-form ref="purchaseTaskFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编码" prop="taskId">
              <el-input v-model="form.taskId" placeholder="请输入任务编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="materialId">
              <material-select v-model="form.materialId" v-model:code="form.materialCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <supplier-select v-model="form.supplierId" :material-id="form.materialId"></supplier-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价" prop="price">
              <el-input v-model="form.price" placeholder="请输入单价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预估交期最早日期" prop="estimateEarlyDate">
              <el-date-picker
                v-model="form.estimateEarlyDate"
                clearable
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择预估交期最早日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预估交期最晚日期" prop="estimateLatestDate">
              <el-date-picker
                v-model="form.estimateLatestDate"
                clearable
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择预估交期最晚日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PurchaseTask" lang="ts">
import { listPurchaseTask, getPurchaseTask, delPurchaseTask, addPurchaseTask, updatePurchaseTask } from '@/api/purchase/purchase';
import { PurchaseTaskVO, PurchaseTaskQuery, PurchaseTaskForm } from '@/api/purchase/purchase/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const purchaseTaskList = ref<PurchaseTaskVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const purchaseTaskFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PurchaseTaskForm = {
  purchaseTaskId: undefined,
  materialId: undefined,
  materialCode: undefined,
  supplierId: undefined,
  phoneNumber: undefined,
  price: undefined,
  amount: undefined,
  totalPrice: undefined,
  estimateEarlyDate: undefined,
  estimateLatestDate: undefined,
  remark: undefined,
  taskId: undefined
};
const data = reactive<PageData<PurchaseTaskForm, PurchaseTaskQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    materialId: undefined,
    materialCode: undefined,
    supplierId: undefined,
    phoneNumber: undefined,
    price: undefined,
    amount: undefined,
    totalPrice: undefined,
    estimateEarlyDate: undefined,
    estimateLatestDate: undefined,
    taskId: undefined,
    params: {}
  },
  rules: {
    purchaseTaskId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    materialId: [{ required: true, message: '物料Id不能为空', trigger: 'blur' }],
    materialCode: [{ required: true, message: '物料编码不能为空', trigger: 'blur' }],
    supplierId: [{ required: true, message: '供应商Id不能为空', trigger: 'blur' }],
    phoneNumber: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
    price: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
    amount: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
    totalPrice: [{ required: true, message: '总价不能为空', trigger: 'blur' }],
    estimateEarlyDate: [{ required: true, message: '预估交期最早日期不能为空', trigger: 'blur' }],
    estimateLatestDate: [{ required: true, message: '预估交期最晚日期不能为空', trigger: 'blur' }],
    remark: [{ required: false, message: '备注不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询采购任务列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPurchaseTask(queryParams.value);
  purchaseTaskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  purchaseTaskFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PurchaseTaskVO[]) => {
  ids.value = selection.map((item) => item.purchaseTaskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加采购任务';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PurchaseTaskVO) => {
  reset();
  const _purchaseTaskId = row?.purchaseTaskId || ids.value[0];
  const res = await getPurchaseTask(_purchaseTaskId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改采购任务';
};

/** 提交按钮 */
const submitForm = async () => {
  loading.value = true;
  await proxy?.$modal.confirm('是否确认修改当前的采购数据？').finally(() => (loading.value = false));

  purchaseTaskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.totalPrice = form.value.amount * form.value.price;
      if (form.value.purchaseTaskId) {
        await updatePurchaseTask(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPurchaseTask(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PurchaseTaskVO) => {
  const _purchaseTaskIds = row?.purchaseTaskId || ids.value;
  await proxy?.$modal.confirm('是否确认删除采购任务编号为"' + _purchaseTaskIds + '"的数据项？').finally(() => (loading.value = false));
  await delPurchaseTask(_purchaseTaskIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/purchaseTask/export',
    {
      ...queryParams.value
    },
    `purchaseTask_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
